
package com.task.base;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.widget.RemoteViews;

public class SettingActivity extends PreferenceActivity {

    private NotificationManager nm;

    private Notification notification;

    private int notificationId = 597777;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.layout.setting);

        nm = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
        notification = new Notification(R.drawable.icon, getString(R.string.app_name),
                System.currentTimeMillis());
        notification.contentView = new RemoteViews(getPackageName(), R.layout.notification);
        Intent openTaskIntent = new Intent(this, MyTaskManagerActivity.class);
        openTaskIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, openTaskIntent, 0);
        notification.contentIntent = pendingIntent;
        notification.flags = Notification.FLAG_ONGOING_EVENT;

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        sp.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                if (key.equals("system")) {
                    Boolean autoBack = sharedPreferences.getBoolean("system", false);
                    if (autoBack) {
                        nm.notify(notificationId, notification);
                    } else {
                        nm.cancel(notificationId);
                    }
                }
            }

        });

    }

    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
        if (preference != null && preference.getKey().equals("create_shortcut")) {
            Util.addShortcut(this);
        }

        return super.onPreferenceTreeClick(preferenceScreen, preference);
    }

}
